const express=require("express");
const axios = require('axios');
const tunnel = require('tunnel')

var router=express.Router();
router.post("/",(req,res)=>{
      const {messages} = req.body;

      const agent = tunnel.httpsOverHttp({
            proxy: {
                  host: '127.0.0.1',
                  port: 7890,
            }
      });
      const YOUR_API_KEY = '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'
      axios.post('https://api.openai.com/v1/chat/completions',{
            model: 'gpt-3.5-turbo',
            messages,
            stream:true
      },{
            httpsAgent: agent,
            headers: {
                  Authorization: `Bearer ${YOUR_API_KEY}`,
            },
            responseType: 'stream',
            timeout: 60 * 1000,
      }).then(result=>{
            const stream = result.data;
            res.set('Content-Type', 'text/event-stream');//流文本，文本的即时处理
            res.set('Transfer-Encoding', 'chunked');//内容分块
            stream.on('data', (chunk) => {
                const allStr = chunk.toString()
                // const allStr = decoder.decode(chunk)
                //   const arrayBuffer = chunk.data
                //   const uint8Array = new Uint8Array(chunk)
                //   let allStr = String.fromCharCode.apply(null, uint8Array)
                const urlStr = encodeURIComponent(allStr)
                const newBuffer = Buffer.from(urlStr)
                res.write(newBuffer);

            });
            stream.on('end', () => {
                  res.end();
            });

            // const data = result.data.choices[0].message
            // res.send(JSON.stringify({
            //       code:200,
            //       data
            // }));
      }).catch(e=>{
            console.log(e)
            res.send(JSON.stringify({
                  code:500,
                  message:'访问chatgpt失败，请稍后再试'
            }))
      })
})
module.exports=router;
//http://localhost:3000/indexa